<template>
  <div class="professional-process-designer">
    <div class="designer-toolbar">
      <div class="toolbar-left">
        <el-button-group>
          <el-button size="small" icon="el-icon-upload" @click="importProcess">导入</el-button>
          <el-button size="small" icon="el-icon-download" @click="exportProcess">导出</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="resetProcess">重置</el-button>
        </el-button-group>
      </div>
      <div class="toolbar-right">
        <el-button icon="el-icon-plus" size="small" @click="scale += 10" :disabled="scale >= 150" circle></el-button>
        <span class="scale-text">{{ scale }}%</span>
        <el-button icon="el-icon-minus" size="small" @click="scale -= 10" :disabled="scale <= 40" circle></el-button>
        <el-button @click="validate" type="success" size="small">校验流程</el-button>
        <el-button @click="toggleFullscreen" type="primary" size="small" icon="el-icon-full-screen">全屏</el-button>
      </div>
    </div>
    
    <div class="design-content" :style="'transform: scale('+ scale / 100 +');'">
      <process-tree ref="process-tree" @selectedNode="nodeSelected"/>
    </div>
    
    <!-- 节点配置抽屉 -->
    <el-drawer 
      :title="selectedNode.name" 
      :visible.sync="showConfig"
      :size="selectedNode.type === 'CONDITION' ? '600px':'500px'"
      direction="rtl" 
      :modal="false" 
      destroy-on-close
    >
      <div slot="title">
        <el-input v-model="selectedNode.name" size="medium" v-show="showInput"
                  style="width: 300px" @blur="showInput = false"></el-input>
        <el-link v-show="!showInput" @click="showInput = true" style="font-size: medium">
          <i class="el-icon-edit" style="margin-right: 10px"></i>
          {{selectedNode.name}}
        </el-link>
      </div>
      <div class="node-config-content">
        <node-config/>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import ProcessTree from './ProcessTree.vue'
import NodeConfig from './node/config/NodeConfig.vue'

export default {
  name: "ProcessDesignProfessional",
  components: { ProcessTree, NodeConfig },
  data() {
    return {
      scale: 100,
      selected: {},
      showInput: false,
      showConfig: false
    }
  },
  computed: {
    selectedNode() {
      return this.$store.state.selectedNode || {}
    }
  },
  mounted() {
    // 只有在创建新流程时才初始化流程数据
    if (!this.$store.state.isEdit) {
      this.initProcessData()
    }
  },
  methods: {
    // 初始化流程数据
    initProcessData() {
      const processData = {
        id: "root",
        parentId: null,
        type: "ROOT",
        name: "发起人",
        props: {
          assignedUser: []
        },
        children: {}
      }
      this.$store.commit('loadForm', { formItems: [], process: processData })
    },
    
    // 导入流程
    importProcess() {
      // 创建文件输入元素
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.json'
      input.onchange = (event) => {
        const file = event.target.files[0]
        if (file) {
          const reader = new FileReader()
          reader.onload = (e) => {
            try {
              const processData = JSON.parse(e.target.result)
              // 验证文件格式
              if (this.validateImportData(processData)) {
                // 加载流程数据到设计器
                this.loadProcessData(processData)
                this.$message.success('流程导入成功')
              } else {
                this.$message.error('文件格式不正确，请选择有效的流程文件')
              }
            } catch (error) {
              this.$message.error('文件解析失败：' + error.message)
            }
          }
          reader.readAsText(file)
        }
      }
      input.click()
    },
    
    // 验证导入数据格式
    validateImportData(data) {
      return data && 
             typeof data === 'object' && 
             (data.processConfig || data.processName)
    },
    
    // 加载流程数据
    loadProcessData(processData) {
      if (processData.processConfig) {
        // 如果包含流程配置，直接加载
        this.$store.commit('loadForm', { 
          formItems: processData.formConfig || [], 
          process: processData.processConfig 
        })
      } else {
        // 否则使用默认结构
        this.initProcessData()
      }
    },
    
    // 导出流程
    exportProcess() {
      const processData = this.$store.state.design.process
      const formItems = this.$store.state.design.formItems
      
      // 构建完整的导出数据
      const exportData = {
        processName: '流程模板',
        description: '从流程设计器导出的流程模板',
        category: '自定义',
        icon: 'el-icon-s-operation',
        templateVersion: '1.0',
        exportTime: new Date().toISOString(),
        exportedBy: this.$store.state.user.name || '未知用户',
        formConfig: formItems,
        processConfig: processData
      }
      
      const dataStr = JSON.stringify(exportData, null, 2)
      const dataBlob = new Blob([dataStr], {type: 'application/json'})
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement('a')
      link.href = url
      link.download = `process_template_${new Date().getTime()}.json`
      link.click()
      URL.revokeObjectURL(url)
      this.$message.success('流程已导出')
    },
    
    // 重置流程
    resetProcess() {
      this.$confirm('确定要重置流程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.initProcessData()
        this.$message.success('流程已重置')
      })
    },
    
    // 校验流程
    validate() {
      // 先进行前端校验
      this.$refs["process-tree"].validateProcess()
      
      // 然后进行后端增强校验
      const processConfig = this.$store.state.design.process
      if (processConfig) {
        this.$http.post('/processes/validate', {
          processConfig: JSON.stringify(processConfig)
        })
          .then(response => {
            console.log('后端验证结果', response)
            if (response.code === 200) {
              if (response.data.valid) {
                if (response.data.warnings && response.data.warnings.length > 0) {
                  this.$message.warning(response.data.message)
                } else {
                  console.log('验证通过', response)
                  this.$message.success(response.data.message)
                }
              } else {
                this.$message.error(response.data.message)
                if (response.data.errors && response.data.errors.length > 0) {
                  console.error('验证错误:', response.data.errors)
                }
              }
            } else {
              this.$message.error(response.message || '验证失败')
            }
          })
          .catch(error => {
            console.error('后端验证失败:', error)
            this.$message.error('后端验证失败，请检查网络连接')
          })
      }
    },
    
    // 节点选中
    nodeSelected(node) {
      console.log('配置节点', node)
      this.showConfig = true
    },
    
    // 切换全屏
    toggleFullscreen() {
      if (!document.fullscreenElement) {
        this.$el.requestFullscreen().then(() => {
          this.$message.success('已进入全屏模式，按ESC退出')
        }).catch(err => {
          this.$message.error('全屏失败：' + err.message)
        })
      } else {
        document.exitFullscreen().then(() => {
          this.$message.info('已退出全屏模式')
        }).catch(err => {
          this.$message.error('退出全屏失败：' + err.message)
        })
      }
    }
  },
  watch: {
    selectedNode: {
      deep: true,
      handler(node) {
        console.log("更新节点", node)
        if (this.$refs["process-tree"]) {
          this.$refs["process-tree"].nodeDomUpdate(node)
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.professional-process-designer {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  min-height: 600px;
}

.designer-toolbar {
  padding: 6px 10px;
  background: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 40px;
}

.design-content {
  flex: 1;
  position: relative;
  min-height: 900px;
  transform-origin: 50% 0px 0px;
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.scale-text {
  margin: 0 10px;
  font-size: 15px;
  color: #7a7a7a;
  width: 50px;
  text-align: center;
}

.node-config-content {
  padding: 0 20px 20px;
}

/deep/ .el-drawer__body {
  overflow-y: auto;
}
</style>
